import { Form, Input, InputNumber, Modal, Radio, Select, message } from "antd";
import React from "react";
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-react/locale';
import styles from "./index.less";
import { languageModelUpdate, modelTemplateList } from "@/services/languageModel";

class AddLanguageModel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      templateList: [],
      facInfo: {},
      loading: false
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  initModal = () => {
    this.getTemplateList()
    this.setState({ visible: true })
  }

  getTemplateList = async () => {
    const res = await modelTemplateList()
    res.push({ api: "", modelNameList: [], name: "自定义", type: 6 })
    this.setState({ templateList: res })
  }

  cancelModal = () => {
    this.props.form.resetFields()
    this.setState({ visible: false, facInfo: {}, loading: false })
  }

  doOkValidate = () => {
    const that = this;
    this.props.form.validateFields((error, values) => {
      if (!error) {
        that.doOk(values)
      }
    })
  }

  doOk = async values => {
    // const { currentUser } = this.state;
    const { facInfo } = this.state;
    if (!values.api) {
      values.api = facInfo.modelApiMap[values.modelName]
    }
    values.type = facInfo.type
    let { fac, ...obj } = values;
    const copyObj = obj;
    this.setState({ loading: true }, async () => {
      // const res = await languageModelUpdate({ ...copyObj, urlPrefix: currentUser.tenantId == "1" ? "admin" : undefined })
      const res = await languageModelUpdate(copyObj)
      this.setState({ loading: false }, () => {
        if (res.code == -1) { } else {
          message.info(res.message)
          this.props.refreshParent()
          this.cancelModal()
        }
      })
    })
  }

  changeFac = value => {
    this.props.form.resetFields(["modelName"])
    const { templateList } = this.state;
    const infoIndex = templateList.findIndex(item => item.name === value)
    if (infoIndex != -1) {
      const facInfo = templateList[infoIndex]
      this.setState({ facInfo }, () => {
        //若模型ID数组只有1个 则默认选中
        if (facInfo.modelApiMap && Object.keys(facInfo.modelApiMap).length == 1) {
          this.props.form.setFieldsValue({ modelName: Object.keys(facInfo.modelApiMap)[0] })
        }
      })
    }
  }

  render() {
    const { form: { getFieldDecorator, getFieldValue } } = this.props;
    const { visible, templateList, facInfo, loading } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    return (
      <Modal
        title={formatMessage({ id: 'addModel.title' })}
        okText={formatMessage({ id: 'addModel.confirm' })}
        cancelText={formatMessage({ id: 'addModel.cancel' })}
        onCancel={this.cancelModal}
        onOk={this.doOkValidate}
        visible={visible}
        width={800}
        bodyStyle={{ height: '600px', overflowY: 'scroll' }}
        confirmLoading={loading}
      >
        <Form {...formItemLayout}>
          <Form.Item label={formatMessage({ id: 'addLanguageModel.modelName' })} extra={formatMessage({ id: 'addLanguageModel.modelNameDesc' })}>
            {getFieldDecorator("name", { rules: [{ required: true, message: formatMessage({ id: 'addLanguageModel.required.modelName' }) }] })(<Input placeholder={formatMessage({ id: 'addLanguageModel.placeholder.enterModelName' })} />)}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'addLanguageModel.modelType' })} extra={formatMessage({ id: 'addLanguageModel.modelTypeDesc' })}>
            {getFieldDecorator("modelType", { initialValue: '1', rules: [{ required: true, message: formatMessage({ id: 'addLanguageModel.required.modelType' }) }] })(
              <Radio.Group>
                <Radio value={'1'}>{formatMessage({ id: 'addLanguageModel.internalModel' })}</Radio>
                <Radio value={'2'}>{formatMessage({ id: 'addLanguageModel.externalModel' })}</Radio>
              </Radio.Group>
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'addLanguageModel.provider' })} extra={formatMessage({ id: 'addLanguageModel.providerDesc' })}>
            {getFieldDecorator("fac", { rules: [{ required: true, message: formatMessage({ id: 'addLanguageModel.required.provider' }) }] })(
              <Select placeholder={formatMessage({ id: 'addLanguageModel.placeholder.selectProvider' })} onChange={this.changeFac}>
                {templateList.map((item, index) => {
                  return <Select.Option key={index} value={item.name}>{item.name}</Select.Option>
                })}
              </Select>
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'addLanguageModel.modelId' })}>
            {getFieldDecorator("modelName", { rules: [{ required: true, message: formatMessage({ id: 'addLanguageModel.required.modelId' }) }] })(
              facInfo.modelApiMap && Object.keys(facInfo.modelApiMap).length > 0 ? (
                <Radio.Group>
                  {Object.keys(facInfo.modelApiMap).map((item, index) => {
                    return <Radio key={index} value={item}>{item}</Radio>
                  })}
                </Radio.Group>
              ) : (
                <Input placeholder={formatMessage({ id: 'addLanguageModel.modelIdDesc' })} />
              )
            )}
          </Form.Item>
          {/**自定义有接口地址 */}
          {facInfo.type == 6 ? (
            <Form.Item label={formatMessage({ id: 'addLanguageModel.apiUrl' })}>
              {getFieldDecorator("api", { rules: [{ required: true, message: formatMessage({ id: 'addLanguageModel.required.apiUrl' }) }] })(<Input placeholder={formatMessage({ id: 'addLanguageModel.apiUrlPlaceholder' })} />)}
            </Form.Item>
          ) : null}
          {facInfo.type != 1 ? (
            <Form.Item label={formatMessage({ id: 'addLanguageModel.apiKey' })} extra={formatMessage({ id: 'addLanguageModel.apiKeyDesc' })}>
              {getFieldDecorator("apiKey", { rules: [{ required: true, message: formatMessage({ id: 'addLanguageModel.required.apiKey' }) }] })(
                <Input.Password visibilityToggle={false} placeholder={formatMessage({ id: 'addLanguageModel.apiKeyPlaceholder' })} autoComplete="new-password" />
              )}
            </Form.Item>
          ) : null}
          {/**文心一言有SecretKey */}
          {facInfo.type == 3 ? (
            <Form.Item label={formatMessage({ id: 'addLanguageModel.secretKey' })}>
              {getFieldDecorator("secretKey", { rules: [{ required: true, message: formatMessage({ id: 'addLanguageModel.required.secretKey' }) }] })(
                <Input.Password visibilityToggle={false} placeholder={formatMessage({ id: 'addLanguageModel.secretKeyPlaceholder' })} autoComplete="new-password" />
              )}
            </Form.Item>
          ) : null}
          <Form.Item label={formatMessage({ id: 'addLanguageModel.topP' })} extra={formatMessage({ id: 'addLanguageModel.topPDesc' })}>
            {getFieldDecorator("topP", { initialValue: 1.0 })(<Input />)}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'addLanguageModel.temperature' })} extra={formatMessage({ id: 'addLanguageModel.temperatureDesc' })}>
            {getFieldDecorator("temperature", { initialValue: 0.7 })(<Input />)}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'addLanguageModel.tokens' })} extra={formatMessage({ id: 'addLanguageModel.tokensDesc' })}>
            {getFieldDecorator("tokens", { initialValue: 4096 })(<Input />)}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'addLanguageModel.description' })}>
            {getFieldDecorator("comment")(<Input.TextArea autoSize rows={3} />)}
          </Form.Item>
        </Form>
        <div className={styles.foot}>
          <p>{formatMessage({ id: 'addLanguageModel.defaultModels' })}</p>
          {templateList.map((item, index) => {
            return item.modelNameList && item.modelNameList.length > 0 ? (
              <p key={index}>
                {item.name}：
                {item.modelNameList.map((model, modelIndex) => {
                  return model + (modelIndex === item.modelNameList.length - 1 ? '' : '、')
                })}
              </p>
            ) : null
          })}
          <p>{formatMessage({ id: 'addLanguageModel.apiFixed' })}</p>
          <p>{formatMessage({ id: 'addLanguageModel.customTip' })}</p>
        </div>
      </Modal>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(AddLanguageModel))